﻿var familyTree = {
    config: {},
    targetX: 0,
    targetY: 0,
    tagCounter: 0,
    img: undefined,
    tags: [],
    tagShown: undefined,
    descendants: {},
    tree: {},
    addTag: function (tag) {
        var remove = '';
        if (familyTree.config.edit)
            remove = '<span class="remove" onclick="familyTree.removeTag(' + tag.Id + ')">(Remove)</span>';
        //Adds a new list item below image. Also adds events inline since they are dynamically created after page load
        $("div.FamilyTreePeople").append('<span class="clickable" id="hotspot-item-' + tag.Id + '" onmouseover="familyTree.showTag(' + tag.Id + ')" onmouseout="familyTree.hideTag(' + tag.Id + ')">' + tag.name + remove + '</span>&nbsp &nbsp');
        var name = tag.name;
        var offset = familyTree.img.offset();
        //tag.x = offset.left + tag.x;
        //tag.y = offset.top + tag.y;
        if (tag.url != undefined && tag.url != '')
            name = '<span class ="viewDescendants clickable" onclick="familyTree.switchTag(' + tag.Id + ')">' + tag.name + '</span>'
        //Adds a new hotspot to image
        $("#tag-wrapper").append('<div id="hotspot-' + tag.Id + '" class="hotspot" style="left:' + tag.x + 'px; top:' + tag.y + 'px;"><span>' + name +
        ' </span></div>');
        familyTree.tags[familyTree.tagCounter] = tag.Id;
        familyTree.descendants[tag.Id] = tag;
        familyTree.tree[tag.Id] = tag;
        familyTree.tagCounter++;
    },
    createTag: function () {
        var newTag = { name: $("#tag-name").val(), url: $("#family-image-url").text(), x: familyTree.targetX, y: familyTree.targetY, Id: 0, parentId: familyTree.tagShown.Id };
        familyTree.closeTagInput();
        $.postAntiForgery(familyTree.config.addUrl, newTag, function (data) {
            familyTree.addTag(data);
        });
    },
    createStartTag: function (config) {
        var newTag = { name: $("#ftname").val(), url: $("#fturl").val(), x: 0, y: 0, Id: 0 };
        familyTree.config = config;
        familyTree.closeTagInput();
        $.postAntiForgery(familyTree.config.addUrl, newTag, function (data) {
            familyTree.tagShown = data;
            $("input.FamilyMemberId").val(data.Id);
            familyTree.init(data);
        });
    },
    closeTagInput: function () {
        $("#tag-target").fadeOut();
        $("#tag-input").fadeOut();
        $("#tag-name").val("");
        $("#family-image-url").html("")
    },
    hideTag: function (i) {
        $("#hotspot-" + i).removeClass("hotspothover");
    },
    showTag: function (i) {
        $("#hotspot-" + i).addClass("hotspothover");
    },
    removeTag: function (i, del) {
        if (del == undefined || del) {
            $.postAntiForgery(familyTree.config.deleteUrl, { Id: i }, function (data) {
                ; //Do nothing for now
            });
        }
        $("#hotspot-item-" + i).fadeOut().remove();
        $("#hotspot-" + i).fadeOut().remove();
    },
    clearTags: function () {
        for (x in familyTree.tags) {
            familyTree.removeTag(familyTree.tags[x], false);
        }
        familyTree.tags = [];
        familyTree.tagCounter = 0;
        familyTree.descendants = {};
    },
    switchTag: function (i) {
        var selected = familyTree.tree[i];
        familyTree.tree[familyTree.tagShown.Id] = familyTree.tagShown;
        familyTree.tagShown = selected;
        familyTree.img.attr("src", selected.url)
        .load(function () {
            $(this).parent().css({ width: this.width, height: this.height });
        });

        familyTree.clearTags();
        $.postAntiForgery(familyTree.config.startUrl, { Id: familyTree.tagShown.Id }, function (data) {
            for (t in data) {
                familyTree.addTag(data[t]);
            }
        });
        familyTree.createHiearchy();
    },
    createHiearchy: function () {
        var hiearchy = $("div.FamilyTree div.hiearchy");
        var tag = familyTree.tagShown;
        var tags = '';
        var count = 0;
        while (tag != undefined) {
            tags = '<span class ="viewDescendants clickable" onclick="familyTree.switchTag(' + tag.Id + ')">' + tag.name + '</span><span>-</span>' + tags;
            tag = familyTree.tree[tag.parentId];
            count++;
        }
        if (count > 1)
            hiearchy.html(tags);
        else
            hiearchy.html('');
    },
    pickImage: function () {
        jQuery(this).trigger("orchard-admin-pickimage-open", {
            img: null,
            uploadMediaPath: 'images',
            callback: function (data) {
                var url = data.img.src;
                $("#family-image-url").html(url);
            }
        });
    },
    init: function (tag, configuration) {
        $('input.OrchardMedia').live('click', familyTree.pickImage);
        if (configuration)
            familyTree.config = configuration;
        //Dynamically wrap image
        familyTree.tagShown = tag;
        var tagWrapper = $('<div id="tag-wrapper"></div>');
        familyTree.img = $('<img class="FamilyTree" src="' + familyTree.tagShown.url + '" title="' + familyTree.tagShown.name + ' Family Tree"/>');
        var width = familyTree.img.width();
        if (width == 0)
            width = 645;
        var height = familyTree.img.height();
        if (height == 0)
            height = 485;
        familyTree.img.load(function () {
            $(this).parent().css({ width: this.width, height: this.height });
        });
        tagWrapper.append(familyTree.img);
        $("div.FamilyTree").append(tagWrapper);
        $("div.FamilyTree").append('<div class="hiearchy"></div><div class="FamilyTreePeople">People in the photo- </div>');
        familyTree.img.attr("src", familyTree.tagShown.url);

        //Dynamically size wrapper div based on image dimensions
        tagWrapper.css({ width: width, height: height });

        //Append #tag-target content and #tag-input content
        tagWrapper.append('<div id="tag-target"></div><div id="tag-input"><label for="tag-name"> Name:</label><input type="text" id="tag-name">' +
        '<label for="tag-name"> Drill Down Image:</label><label style="font-size:.8em;" id="family-image-url"></label> <input type="button" value="Choose Image" class="OrchardMedia mce_mediapicker"/>' +
        '<input type="button" class="familyTree" value="Add Tag"/><input type="button" class="familyTreeCancel" value="Cancel"/></div>');

        //$("#tag-wrapper").click(function(e){
        if (familyTree.config.edit) {
            familyTree.img.click(function (e) {
                //Determine area within element that mouse was clicked
                var mouseX = e.pageX - $("#tag-wrapper").offset().left;
                var mouseY = e.pageY - $("#tag-wrapper").offset().top;

                //Get height and width of #tag-target
                targetWidth = $("#tag-target").outerWidth();
                targetHeight = $("#tag-target").outerHeight();

                //Determine position for #tag-target
                familyTree.targetX = mouseX - targetWidth / 2;
                familyTree.targetY = mouseY - (targetHeight / 2);

                //Determine position for #tag-input
                inputX = mouseX + targetWidth / 2;
                inputY = familyTree.targetY;

                //Animate if second click, else position and fade in for first click
                if ($("#tag-target").css("display") == "block") {
                    $("#tag-target").animate({ left: familyTree.targetX, top: familyTree.targetY }, 500);
                    $("#tag-input").animate({ left: inputX, top: inputY }, 500);
                } else {
                    $("#tag-target").css({ left: familyTree.targetX, top: familyTree.targetY }).fadeIn();
                    $("#tag-input").css({ left: inputX, top: inputY }).fadeIn();
                }

                //Give input focus
                $("#tag-name").focus();
            });
        }
        //If cancel button is clicked
        $('input.familyTreeCancel').click(function () {
            familyTree.closeTagInput();
        });
        //If enter button is clicked within #tag-input
        $("#tag-name").keyup(function (e) {
            if (e.keyCode == 13)
                familyTree.createTag();
        });

        //If submit button is clicked
        $('input.familyTree').click(function () {
            familyTree.createTag();
        });

        $.postAntiForgery(familyTree.config.startUrl, { Id: familyTree.tagShown.Id }, function (data) {
            for (t in data) {
                familyTree.addTag(data[t]);
            }
        });
        familyTree.createHiearchy();
    }
}


